
import seaborn as sns
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
import numpy as np


# 1. 数据加载与预处理
df = pd.read_csv('./data/数据挖掘/Bakery.csv')
df['DateTime'] = pd.to_datetime(df['DateTime'])
df['Year'] = df['DateTime'].dt.year
df['Month'] = df['DateTime'].dt.month
df['Day'] = df['DateTime'].dt.day
df['Hour'] = df['DateTime'].dt.hour

# 假设我们已经有Daypart的具体时间段划分，如果没有，可以根据Hour字段自行划分
# 例如：Morning (6-11), Afternoon (12-17), Evening (18-23), Night (0-5)
def assign_daypart(hour):
    if 6 <= hour < 12:
        return 'Morning'
    elif 12 <= hour < 18:
        return 'Afternoon'
    elif 18 <= hour < 24:
        return 'Evening'
    else:
        return 'Night'

df['Daypart'] = df['Hour'].apply(assign_daypart)

# 2. 分析不同时间段的购买行为差异
daypart_sales = df.groupby('Daypart')['TransactionNo'].count()
daypart_sales.plot(kind='bar')
plt.title('Sales Distribution by Daypart')
plt.xlabel('Daypart')
plt.ylabel('Number of Transactions')
plt.show()

# 3. 分析客户购买行为的季节性变化
# 按月份分组统计销售数量
monthly_sales = df.groupby('Month')['TransactionNo'].count()
# 可视化月份销售情况
monthly_sales.plot(kind='bar')
plt.title('Monthly Sales Distribution')
plt.xlabel('Month')
plt.ylabel('Number of Transactions')
plt.show()



df['DateTime'] = pd.to_datetime(df['DateTime'])
df['Year'] = df['DateTime'].dt.year
df['Month'] = df['DateTime'].dt.month
df['DayOfWeek'] = df['DateTime'].dt.dayofweek
df['Weekend'] = (df['DayOfWeek'] >= 5).astype(int)

# 数据预处理：填充缺失值（如果有）
# 假设数据集中没有缺失值，因此这一步可以省略或根据实际情况处理

# 分析哪些商品的销售量将持续增长
# 使用时间序列预测方法（如Holt-Winters）对每个商品进行预测
def forecast_sales(item, df, forecast_period=12):
    item_df = df[df['Items'] == item]
    item_df.set_index('DateTime', inplace=True)
    monthly_sales = item_df.resample('ME').size()
    model = ExponentialSmoothing(monthly_sales, trend='add', seasonal='add', seasonal_periods=12).fit()
    forecast = model.forecast(forecast_period)
    return forecast


# 分析各月份的销售高峰期会出现在哪些商品上
monthly_sales = df.groupby(['Items', 'Month']).size().unstack(fill_value=0)
peak_months = monthly_sales.idxmax(axis=1)

# 分析周末和工作日的销售差异
weekday_sales = df.groupby(['Items', 'Weekend']).size().unstack(fill_value=0)
weekday_sales.columns = ['Weekday Sales', 'Weekend Sales']
weekday_sales['Difference'] = weekday_sales['Weekend Sales'] - weekday_sales['Weekday Sales']

# 面包店的整体销售趋势
total_monthly_sales = df.groupby('DateTime').size().resample('ME').sum()

# 预测是否有可能出现新的热销商品
# 基于历史增长率来预测（简化方法）
growth_rates = {}
for item in df['Items'].unique():
    item_df = df[df['Items'] == item]
    monthly_sales_item = item_df.groupby(item_df['DateTime'].dt.to_period('M')).size()
    growth_rate = monthly_sales_item.pct_change().mean()
    growth_rates[item] = growth_rate

potential_hot_item = max(growth_rates, key=growth_rates.get)


# 2. 销售高峰期可视化
peak_months_df = peak_months.reset_index()
peak_months_df.columns = ['Items', 'Peak Month']
plt.figure(figsize=(12, 6))
sns.boxplot(x='Peak Month', y='Items', data=peak_months_df, orient='h')
plt.title('Peak Sales Months for Each Item')
plt.xlabel('Month')
plt.ylabel('Items')
plt.show()

# 3. 周末和工作日销售差异可视化
plt.figure(figsize=(10, 8))
weekday_sales['Difference'].sort_values().plot(kind='barh')
plt.title('Sales Difference Between Weekend and Weekday')
plt.xlabel('Sales Difference')
plt.ylabel('Items')
plt.show()

# 4. 整体销售趋势可视化
plt.figure(figsize=(10, 5))
plt.plot(total_monthly_sales.index, total_monthly_sales.values, marker='o')
plt.title('Overall Monthly Sales Trend')
plt.xlabel('Month')
plt.ylabel('Total Sales')
plt.grid(True)
plt.show()

# 输出潜在热销商品
print("Potential hot item based on growth rate:", potential_hot_item)

# 示例：预测某个商品的销售量（这里以'Bread'为例）
forecasted_sales_bread = forecast_sales('Bread', df)
# 可视化部分
# 1. 商品销售量预测可视化
plt.figure(figsize=(10, 5))
plt.plot(forecasted_sales_bread, marker='o')
plt.title('Forecasted Monthly Sales for Bread')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.grid(True)
plt.show()

df['DateTime'] = pd.to_datetime(df['DateTime'])

# 以'Bread'为例进行预测
item = 'Bread'
item_df = df[df['Items'] == item]
item_df.set_index('DateTime', inplace=True)
# 重采样频率为'M'（月末）
monthly_sales = item_df.resample('ME').size()

# 使用Holt-Winters方法进行预测
model = ExponentialSmoothing(monthly_sales, trend='add', seasonal='add', seasonal_periods=12).fit()
forecast = model.forecast(12)  # 预测未来12个月的销售量

# 使用历史数据中的最后12个月作为“未来”数据来计算MSE和RMSE（仅用于示例）
actual_sales = monthly_sales[-13:-1].tolist()  # 取最后12个月的实际销售量（不包括当前月）

# 计算MSE和RMSE
mse = mean_squared_error(actual_sales, forecast)
rmse = np.sqrt(mse)
print(f"MSE: {mse}")
print(f"RMSE: {rmse}")

# 可视化预测结果与实际销售量的对比图
plt.figure(figsize=(10, 5))
plt.plot(monthly_sales.index[-13:-1], monthly_sales.values[-13:-1], marker='o', label='Actual Sales')  # 修改了这里
# 修正后的pd.date_range()函数调用和预测值索引
forecast_index = pd.date_range(start=monthly_sales.index[-1], periods=12, freq='ME')
plt.plot(forecast_index, forecast, marker='x', label='Forecasted Sales')
plt.title('Actual vs Forecasted Monthly Sales for Bread')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.show()

